import re
from rest_framework import serializers

from users.models import User


# 指定序列化器
class UserSerializer(serializers.ModelSerializer):
    """
    用户序列化器
    """

    class Meta:
        # 指定模型类
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'password')
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5
            },
            'password': {
                'max_length': 20,
                'min_length': 8,
                'write_only': True
            }
        }

    # 手机号格式验证
    def validate_mobile(self, value):
        if not re.match('1[3-9]\d{9}', value):
            raise serializers.ValidationError('手机格式错误')
        return value

    # 重写create方法
    def create(self, validated_data):
        # create_user方法可以直接对密码进行加密
        user = User.objects.create_user(**validated_data)

        return user
